import {
  requestGET
} from '../../utils/service'

Page({
  data: {
    scene: ''
  },
  onLoad(options) {
    // 获取scene
    if (!options.scene) return this.showMessage();
    this.setData({
      scene: options.scene
    })
    let that = this;
    wx.showModal({
      title: '提示',
      content: '是否授权用户获取预约信息？',
      success: function (res) {
        if (res.confirm) {
          that.sqAction();
        } else if (res.cancel) {
          console.log('用户点击取消');
          wx.exitMiniProgram();
        }
      }
    });
  },
  jumpTo() {
    wx.reLaunch({
      url: '/pages/index/index' // 首页的路径
    });
  },
  showMessage() {
    wx.showModal({
      title: '提示',
      content: '授权失败，请重新扫码！',
      showCancel: false,
      success: function (res) {
        wx.exitMiniProgram();
      }
    });
  },
  // 授权
  sqAction() {
    wx.showLoading({
      title: '授权中，请稍后...'
    });
    let that = this
    wx.login({
      success: res => {
        this.postSence(res.code)
      },
      fail: (err) => {
        wx.hideLoading();
        //失败操作
        that.showMessage();
      }
    })
  },
  postSence(code) {
    const data = {
      "scene": this.data.scene,
      "wxAuthenticationCode": code,
    }
    requestGET("reservation/queryReservationByQrCode", data).then(res => {
      wx.hideLoading();
      if (res.data?.code == '200') {
        wx.showModal({
          title: '提示',
          content: '授权成功!',
          showCancel: false,
          success: function (res) {
            wx.exitMiniProgram();
          }
        });
      } else {
        console.log('绑定失败', res);
        if (res.data?.code == '1002') {
          wx.setStorageSync('openId', res.data.data)
          // 用户未注册
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              wx.redirectTo({
                url: '/pages/register/index',
              })
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              wx.exitMiniProgram();
            }
          });
        }
      }
    }).catch(err => {
      wx.hideLoading();
      console.log('err====', err);
    })
  }
})